/**
 * http://gupiao.baidu.com/ui/gushitong?count=5&cuid=xxx&format=json&fq_type=front&from=pc&os_ver=1&queryURL=stockdaybar&start=&step=3&stock_code=sz000001&uid=4f0ba713-f6d5-c66b-0c16-429413cd66ed&vv=100
 * @type {String}
 * 今日DIFF = (17416 * 昨天DIFF - 7700 * 前天DIFF - 784 * 昨天收盘价 + 784 * 今天收盘价) / 9828
 * 今日DEA = （前一日DEA X 8/10 + 今日DIF X 2/10）
 * 用（DIF-DEA）*2即为MACD柱状图。
 */
function _diff(diff1, diff2, close1, close) {
  return (17416 * diff1 - 7700 * diff2 - 784 * close1 + 784 * close) / 9828
}

function _dea(dea1, diff) {
  return dea1 * 8 / 10 + diff * 2 / 10;
}

function _macd(diff, dea) {
  return (diff - dea) * 2;
}

//保留几位小数
function _round(now, len) {
  var len = len || 2;
  return parseFloat(now.toFixed(len));
}

/**
 * [recursive recursive + call + callback]
 * @param  {[Function]}   call     [description]
 * @param  {[Array]}   array    [description]
 * @param  {[Int]}   i        [description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
function _recursive(call, array, i, callback) {
  var args = arguments;
  call(i, function() {
    if (args[2] === array.length - 1) {
      if (callback)
        callback.apply(this, arguments);
    } else {
      args[2]++;
      _recursive.apply(this, args);
    }
  });
}

module.exports = {
  macd: function(diff1, diff2,
    dea1, close1, close) {
    var diff0 = _diff(diff1, diff2, close1, close);
    var dea0 = _dea(dea1, diff0);
    var macd0 = _macd(diff0, dea0);
    return {
      diff: diff0,
      dea: dea0,
      macd: macd0
    };
  },
  round: _round,
  recursive: _recursive
};
